Page({
  data: {
    categories: [],
    loading: true,
    refreshing: false,
    searchKeyword: '',
    stats: {
      total: 0,
      active: 0,
      deleted: 0
    }
  },

  onLoad() {
    this.loadCategories()
    this.loadStats()
  },

  onShow() {
    this.loadCategories()
    this.loadStats()
  },

  // 加载分类列表
  async loadCategories() {
    this.setData({ loading: true })
    
    try {
      const result = await wx.cloud.callFunction({
        name: 'categoryManager',
        data: {
          action: 'getAllCategories'
        }
      })

      if (result.result.success) {
        this.setData({
          categories: result.result.data,
          loading: false
        })
        console.log('✅ 分类列表加载成功')
      } else {
        this.setData({ loading: false })
        wx.showToast({
          title: '加载失败',
          icon: 'error'
        })
      }
    } catch (error) {
      this.setData({ loading: false })
      console.error('❌ 加载分类列表失败:', error)
      wx.showToast({
        title: '加载失败',
        icon: 'error'
      })
    }
  },

  // 加载统计数据
  async loadStats() {
    try {
      // 这里可以添加统计相关的云函数调用
      const categories = this.data.categories
      this.setData({
        stats: {
          total: categories.length,
          active: categories.filter(c => c.status === 'active').length,
          deleted: categories.filter(c => c.status === 'deleted').length
        }
      })
    } catch (error) {
      console.error('加载统计数据失败:', error)
    }
  },

  // 添加分类
  addCategory() {
    wx.navigateTo({
      url: '/pages/category-edit/category-edit?mode=add'
    })
  },

  // 编辑分类
  editCategory(e) {
    const category = e.currentTarget.dataset.category
    wx.navigateTo({
      url: `/pages/category-edit/category-edit?mode=edit&id=${category._id}`
    })
  },

  // 删除分类
  deleteCategory(e) {
    const category = e.currentTarget.dataset.category
    
    wx.showModal({
      title: '确认删除',
      content: `确定要删除分类"${category.name}"吗？`,
      success: async (res) => {
        if (res.confirm) {
          wx.showLoading({
            title: '删除中...',
            mask: true
          })

          try {
            const result = await wx.cloud.callFunction({
              name: 'categoryManager',
              data: {
                action: 'deleteCategory',
                categoryId: category._id
              }
            })

            wx.hideLoading()

            if (result.result.success) {
              wx.showToast({
                title: '删除成功',
                icon: 'success'
              })
              this.loadCategories()
              this.loadStats()
            } else {
              wx.showToast({
                title: '删除失败',
                icon: 'error'
              })
            }
          } catch (error) {
            wx.hideLoading()
            console.error('删除分类失败:', error)
            wx.showToast({
              title: '删除失败',
              icon: 'error'
            })
          }
        }
      }
    })
  },

  // 初始化分类数据
  async initCategories() {
    wx.showModal({
      title: '确认初始化',
      content: '这将创建默认的10个分类数据，确定继续吗？',
      success: async (res) => {
        if (res.confirm) {
          wx.showLoading({
            title: '初始化中...',
            mask: true
          })

          try {
            const result = await wx.cloud.callFunction({
              name: 'categoryManager',
              data: {
                action: 'initCategoryData'
              }
            })

            wx.hideLoading()

            if (result.result.success) {
              wx.showToast({
                title: '初始化成功',
                icon: 'success'
              })
              this.loadCategories()
              this.loadStats()
            } else {
              wx.showToast({
                title: result.result.message || '初始化失败',
                icon: result.result.message ? 'none' : 'error'
              })
            }
          } catch (error) {
            wx.hideLoading()
            console.error('初始化分类数据失败:', error)
            wx.showToast({
              title: '初始化失败',
              icon: 'error'
            })
          }
        }
      }
    })
  },

  // 搜索分类
  onSearchInput(e) {
    this.setData({
      searchKeyword: e.detail.value
    })
  },

  // 下拉刷新
  async onPullDownRefresh() {
    this.setData({ refreshing: true })
    await this.loadCategories()
    await this.loadStats()
    this.setData({ refreshing: false })
    wx.stopPullDownRefresh()
  },

  // 分享
  onShareAppMessage() {
    return {
      title: '数智匠心工程 - 分类管理',
      path: '/pages/category-admin/category-admin'
    }
  }
}) 